<template>
  <div class="main-flowAnalysis">
    <div class="flowItem">
      <label for="pet-select" style="margin: 0;margin-right: 10px">管线层:</label>
      <select name="pets" id="pet-select" style="height: 25px;width: 150px" v-model="layerType">
        <option value="未选择">未选择</option>
        <option value="雨水线">雨水管线</option>
        <option value="污水线">污水管线</option>
      </select>
    </div>
    <div class="flowItem">
      <input type="checkbox" v-model="flowSimulate" style="margin: 0;margin-right: 10px" id="horns" name="horns"/>
      <label for="horns" style="margin: 0">水流模拟</label>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
let openLayer = null
let selectEntity = []
// eslint-disable-next-line no-unused-vars
let from
// eslint-disable-next-line no-unused-vars
let dataTable = []
import clearWindow from "@/components/js/clearWindow";
import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";
import arrowPng from '@/assets/img/textures/ArrowOpacity.png'
import "@/components/js/LaserPolylineTrailLinkMaterialProperty";

export default {
  name: "flowAnalysis",
  components: {},
  data() {
    return {
      layerType: '未选择',
      flowSimulate: false,
    };
  },
  mounted() {
    openLayer = null;
    clearWindow()
  },
  methods: {
    computeCircle(radius) {
      var positions = [];
      for (var i = 0; i < 360; i++) {
        var radians = Cesium.Math.toRadians(i);
        positions.push(
            new Cesium.Cartesian2(
                radius * Math.cos(radians),
                radius * Math.sin(radians)
            )
        );
        i += 10;
      }
      return positions;
    },
    loadPipe(url) {
      let liuxiangLayer = window.viewer.dataSources.getByName('liuxiangLayer')[0]
      if (!liuxiangLayer) {
        liuxiangLayer = new Cesium.CustomDataSource('liuxiangLayer')
        window.viewer.dataSources.add(liuxiangLayer)
      }

      if (liuxiangLayer.entities.values.length) {
        liuxiangLayer.entities.removeAll()
      }


      let that = this;
      var ajax = new XMLHttpRequest();
      ajax.open('GET', url, true);
      ajax.withCredentials = true;
      ajax.send();
      ajax.onreadystatechange = function () {
        if (ajax.readyState == 4 && ajax.status == 200) {
          var linefeatures = $.parseJSON(ajax.responseText).features;
          console.log(linefeatures)
          for (var index = 0; index < linefeatures.length; index++) {
            if (linefeatures[index].properties.流向 == '0') {
              var feature = linefeatures[index];
              var coord = feature.geometry.coordinates;
              var coords = [];
              for (var i = 0; i < coord[0].length; i++) {
                coords.push(coord[0][i][0]);
                coords.push(coord[0][i][1]);
                coords.push(1042 || coord[0][i][2]);
              }
              liuxiangLayer.entities.add({
                id: feature.id,
                polylineVolume: {
                  positions: Cesium.Cartesian3.fromDegreesArrayHeights(coords),
                  shape: that.computeCircle(0.5),
                  material: new Cesium.LaserPolylineTrailLinkMaterialProperty(
                      5000,
                      Cesium.Color.fromCssColorString("#346ee0")
                  ),
                  outline: false,
                },
              });
            } else {
              let feature = linefeatures[index];
              let coord = feature.geometry.coordinates;
              let coords = [];
              for (let i = 0; i < coord[0].length; i++) {
                coords.push(coord[0][i][1]);
                coords.push(coord[0][i][0]);
                coords.push(1042 || coord[0][i][2]);
              }
              liuxiangLayer.entities.add({
                id: feature.id,
                polylineVolume: {
                  positions: Cesium.Cartesian3.fromDegreesArrayHeights(coords),
                  shape: that.computeCircle(0.5),
                  material: new Cesium.LaserPolylineTrailLinkMaterialProperty(
                      5000,
                      Cesium.Color.fromCssColorString("#346ee0")
                  ),
                  outline: false,
                },
              });
            }

          }
        }
      }
    },
    async addLine(name) {
      let layer = layersMap.find(l => l.type === name)
      if (!layer) {
        alert('请先添加' + name + '图层')
        return;
      }
      var liuxiangLayer = window.viewer.dataSources.getByName('liuxiangLayer')[0]
      if (!liuxiangLayer) {
        liuxiangLayer = new Cesium.CustomDataSource('liuxiangLayer')
        window.viewer.dataSources.add(liuxiangLayer)
      }

      if (liuxiangLayer.entities.values.length) {
        liuxiangLayer.entities.removeAll()
      }

      // 绘制带流向的graphic
      let data = await fetchData(layer.url)

      data.features.forEach(element => {
        // eslint-disable-next-line no-unused-vars
        let flag = element.properties['流向']
        let customCoordinate = (element.geometry.coordinates[0].flat()).map((it, idx) => {
          if (idx % 3 == 2) {
            return 1042 // 指定线的高度
          } else {
            return it
          }
        })
        // flag == '0' && customCoordinate.reverse()
        liuxiangLayer.entities.add({
          name: '箭头动态特效 地面',
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArrayHeights([
              ...customCoordinate
            ]),
            width: 10,
            material: new dadi.LineFlowMaterial({//动画线材质
              // color: Cesium.Color.CHARTREUSE,
              color: Cesium.Color.fromCssColorString('#132666'),
              duration: 1000, //时长，控制速度
              url: arrowPng
            }),
          }
        });
      });
    },
    clearDraw() {
      window.window.viewer.dadi.draw.clearDraw();
      for (var i = 0; i < selectEntity.length; i++) {
        selectEntity[i].billboard.image = 'img/marker/mark3.png';
      }
      selectEntity = [];
      from = null;
      // $table.bootstrapTable('destroy')
      $('#layerSelect').html('');
      // $('#thead').html('')
      dataTable = []
    },
    qc() {
      openLayer = null;
      this.clearDraw()
      var liuxiangLayer = window.viewer.dataSources.getByName('liuxiangLayer')[0]
      if (liuxiangLayer.entities.values.length) {
        liuxiangLayer.entities.removeAll()
      }
    },
    showOpenLayer() {
      if (openLayer) return;
      openLayer = layui.layer.open({
        type: 1,
        area: ['300px', '300px'], // 宽高
        title: "流向分析", // 不显示标题栏
        offset: ['100px', '20px'],
        closeBtn: 1,
        shade: false,
        shadeClose: false, // 点击遮罩关闭层
        content: `<div>
                        <div class="layui-row" >
                            <div class="layui-col-md6 layui-col-md-offset1">
                                <button type="button" class="layui-btn " style="margin: 3px 0; width: 120px;" onclick="lxClazz.addLine('雨水线')">雨水管线</button> &nbsp;&nbsp;
                                <button type="button" class="layui-btn layui-bg-purple" style="margin: 3px 0; width: 120px;" onclick="lxClazz.addLine('污水线')">污水管线</button> &nbsp;&nbsp;
                                <button type="button" class="layui-btn layui-bg-orange" style="margin: 3px 0; width: 120px;" onclick="lxClazz.qc()">清除</button> &nbsp;&nbsp;
                            </div>
                        </div>
                        <hr />
                    </div>
        `,
        cancel: function (index) {
          // if(confirm('确定要关闭么')){
          // }
          layer.close(index);
          openLayer = null;
          return false; // 阻止默认关闭行为
        },
        success: () => {
        },
        end: () => {
          this.qc();
        }
      });
    },
    handleLayer() {
      let layerType = this.layerType;
      let flowSimulate = this.flowSimulate;
      if (flowSimulate === false) {
        if (layerType === '未选择') {
          this.qc()
        } else {
          this.addLine(layerType);
        }
      } else {
        if (layerType === '未选择') {
          this.qc()
        } else {
          let name = layerType
          let layer = layersMap.find(l => l.type === name)
          if (!layer) {
            alert('请先添加' + name + '图层')
            return;
          }
          this.loadPipe(layer.url)
        }
      }
    }
  },
  watch: {
    layerType() {
      this.handleLayer();
    },
    flowSimulate() {
      this.handleLayer();
    }
  },
  computed: {},
  beforeDestroy() {
    this.qc()
  },
}
</script>

<style scoped>
.main-flowAnalysis {
  position: relative;
  /*height: 100%;*/
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: start;
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
}

.main-flowAnalysis button {
  width: 25% !important;
  background-image: url("../assets/img/button/button.png");
  background-size: 100% 100%;
  background-color: transparent !important;
  height: 48px !important;
}

</style>

<style>
div.panelContent:has(div.main-flowAnalysis) {
  height: auto;
}

.flowAnalysisContainer {
  width: 550px !important;
}

.flowItem {
  display: flex;
}

.flowItem:nth-child(1) {
  padding-left: 30px;
  align-items: center;
}

.flowItem:nth-child(2) {
  padding-right: 30px;
  align-items: center;
}
</style>


<style>
.panelContent:has(div.main-flowAnalysis) {
  padding: 3px
}
.flowAnalysisContainer:has(div.main-flowAnalysis) {
  width: 400px!important;
}
.flowAnalysisContainer:has(div.main-flowAnalysis) .panelFooter{
  height: 20px !important;
}
</style>